
using System.Reflection;
using KinonekoSoftware.Extensions.Reflections;
using KinonekoSoftware.Foundation.UI.Core;

#if WINDOWS

using ControlImpl = System.Windows.Controls.Control;

#else

using ControlImpl = Avalonia.Controls.Control;

#endif

namespace KinonekoSoftware.Foundation.UI
{
    partial class Xplat
    {
        private static IViewLocator _locator;

        private static IViewLocator ViewLocator
        {
            get
            {
                return _locator ??= Ioc.Get<IViewLocator>();
            }
        }
        
        public static ControlImpl Associate(object vm)
        {
            return ViewLocator.Associate(vm) as Control;
        }
        
        public static void InstallView<TView, TViewModel>()
        {
            ViewLocator.InstallView<TView, TViewModel>();
        }

        public static void InstallView(MVVMAssociation association)
        {
            ViewLocator.InstallView(association);
        }

        public static void InstallFromRegisters()
        {
            var implType = ClassStatic.FindInterfaceImplementation<IViewModelRegister>(Assembly.GetEntryAssembly());

            if (implType is null)
            {
                return;
            }

            var list = new List<MVVMAssociation>(32);
            var impl = (IViewModelRegister)Activator.CreateInstance(implType);
            impl?.Register(list);


            foreach (var association in list)
            {
                ViewLocator.InstallView(association);
            }
        }
        
        public static void InstallFromRegisters(Assembly assembly)
        {
            var implType = ClassStatic.FindInterfaceImplementation<IViewModelRegister>(assembly);

            if (implType is null)
            {
                return;
            }

            var list = new List<MVVMAssociation>(32);
            var impl = (IViewModelRegister)Activator.CreateInstance(implType);
            impl?.Register(list);


            foreach (var association in list)
            {
                ViewLocator.InstallView(association);
            }
        }
    }
}